package com.stms.action;

import com.alibaba.fastjson.JSONObject;
import com.stms.pojo.Contract;
import com.stms.pojo.Purchase;
import com.stms.service.PurchaseService;
import com.stms.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Autowired
    private PurchaseService purchaseService;

    private Integer count;

    @PostMapping("/addPurchase")
    public Result addPurchase(@RequestBody Purchase purchase){
        if (purchaseService.addPurchase(purchase)){
            return new Result(200,"add success");
        }else{
            return new Result(500,"add fail");
        }
    }

    @PostMapping("/editPurchase")
    public Result editPurchase(@RequestBody Purchase purchase){
        if (purchaseService.addPurchase(purchase)){
            return new Result(200,"edit success");
        }else{
            return new Result(500,"edit fail");
        }
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody JSONObject obj){
        try{
            String purchaseIds = (String) obj.get("purchaseIds");
            purchaseService.deletaBatch(purchaseIds);
            return new Result(200,"delete success");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(500,"delete fail");
        }
    }

    @PostMapping("/fuzzyQuery")
    public Map fuzzyQuery(Integer pageNum,Integer pageSize,String direction,Purchase purchase){
        Page<Purchase> page = purchaseService.fuzzyQuery(pageNum,pageSize,direction,purchase);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("data",page);
        return map;
    }

    @PostMapping("/findByPage")
    public Map findByPage(Integer pageNum,Integer pageSize){
        if (count!=null&&pageNum>=count){
            pageNum = count;
        }

        Page<Purchase> page = purchaseService.findByPage(pageNum,pageSize);
        count=page.getTotalPages();
        Map<String,Object> map = new HashMap<>();
        map.put("data",page);
        return map;
    }
}
